package cn.vendai.com.service.impl;

import cn.vendai.com.assistant.AIAgent;
import cn.vendai.com.assistant.Assistant;
import cn.vendai.com.service.ChatService;
import dev.langchain4j.community.model.dashscope.QwenChatModel;
import cn.vendai.com.entity.Message;
import cn.vendai.com.repository.MessageRepository;
import dev.langchain4j.service.AiServices;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.function.Consumer;

@Service
public class ChatServiceImpl implements ChatService {

    private final MessageRepository messageRepository;
    private final QwenChatModel qwenChatModel;

    public ChatServiceImpl(MessageRepository messageRepository, QwenChatModel qwenChatModel) {
        this.messageRepository = messageRepository;
        this.qwenChatModel = qwenChatModel;
    }

    /**
     * 处理用户聊天请求
     * @param userId 用户ID
     * @param conversationId 会话ID
     * @param content 用户输入内容
     * @return AI回复内容
     */
    public String chat(String userId, String conversationId, String content) {
        // 1. 保存用户输入
        Message userMsg = new Message();
        userMsg.setUserId(userId);
        userMsg.setConversationId(conversationId);
        userMsg.setRole("user");
        userMsg.setContent(content);
        userMsg.setCreatedAt(Instant.now());
        messageRepository.save(userMsg);

        // 2. 调用大模型
        Assistant assistant = AiServices.create(Assistant.class, qwenChatModel);
        String aiResponse = assistant.chat(content);

        // 3. 保存AI输出
        Message aiMsg = new Message();
        aiMsg.setUserId(userId);
        aiMsg.setConversationId(conversationId);
        aiMsg.setRole("ai");
        aiMsg.setContent(aiResponse);
        aiMsg.setCreatedAt(Instant.now());
        messageRepository.save(aiMsg);

        // 4. 返回结果
        return aiResponse;
    }


}
